#!/usr/bash

usage() {
cat <<< "
  使用方法：在主工程目录执行脚本
  注意：记得先提交完所有的主工程和子模块的代码，免得代码丢失
  用 -p 或者 --push 标志build完推送到云端
  用 -u 或者 --upload 标志上传到miot
  用 -dv 或者 --diffVersion 标志生成代码差异对比版本
  用 -b 或者 --branch 标志并带上分支名来表示用哪个分支的代码合并过来到打包分支打包，默认为master
  --build-branch 标志并带上分支名来设置打包分支名称，默认为build
  用 --path 标志 指定主工程工作区间
  用 -i 或者 --need-install 标志是否需要 npm install 主工程和miot
"
}

# 代码分支
CODE_BRANCH=master
# 打包分支
BUILD_BRANCH=build
# 要对比的版本
DIFF_VERSION=""
# 已经下载的node_modules目录
INSTALLED_NODE_MODULES_PATH="/var/jenkins_home/workspace/com.lumi.miSdkNodeModules/"

project_path="$PWD"

# 解析传入参数
while [ "$1" != "" ]; do
    case $1 in
        -i | --need-install )     needInstall=1
                                  ;;
        -u | --upload )           isUpload=1
                                  ;;
        -p | --push )             isPushRelease=1
                                  ;;
        -h | --help )             usage
                                  exit
                                  ;;
        -b | --branch )           shift; CODE_BRANCH=$1
                                  ;;
        -dv | --diffVersion )     shift; DIFF_VERSION=$1
                                  ;;
        --path )                  shift; project_path="$1"
                                  ;;
        --build-branch  )         shift; BUILD_BRANCH="$1"
                                  ;;
        * )                       usage
                                  exit 1
    esac
    shift
done

cat <<< "
=========project path=========
  "$project_path"
==============================
"
cd "$project_path"

print_section_header() {
cat <<< "
============================================================
  "$1"
=============================="
}

print_section_footer() {
cat <<< "============================================================
"
}


print_status() {
print_section_header "当前工作区状态"
git status && git submodule
print_section_footer
}


installSdkDependencies() {
  print_section_header "npm install按照依赖"
  sdkVersion=`node ${project_path}/Modules/Mijia-CommonFunction-Modules/DevTools/AutoBuild/getSdkVersion.js`
  if [ -d "${INSTALLED_NODE_MODULES_PATH}${sdkVersion}/node_modules" ];then
    echo "当前分支依赖已缓存下来了，从缓存中加载"
    cp -rf "${INSTALLED_NODE_MODULES_PATH}${sdkVersion}/node_modules" $project_path/../../node_modules
  else
    echo "当前分支依赖没缓存下来了，运行npm ci重新安装"
    npm ci
  fi
  print_section_footer
}


# 判断是否需要初始化子模块
print_section_header "初始化/关联子模块"
if [[ "`ls Modules/Mijia-CommonFunction-Modules`" = "" ]] || [[ "`ls Modules/Mijia-CommonUI-Modules`" = "" ]]; then
  echo "初始化子模块。。。"
  git submodule update --init --recursive && npm install && git reset --hard origin/master || { print_status; echo "git操作失败，请检查原因" >&2; exit 1; }
else
  echo "关联子模块。。。"
  git submodule update --init
fi
print_section_footer


print_section_header "切换主工程分支到 "$CODE_BRANCH" 并拉取代码"
# 是否需要切到master分支的最新commit
git fetch origin && git reset --hard HEAD -- && git checkout "$CODE_BRANCH" && git reset --hard "origin/$CODE_BRANCH" && git clean -df || { print_status; echo "git操作失败，请检查原因" >&2; exit 3; }
print_section_footer

# 记录master分支的版本号
masterVersion=`./Modules/Mijia-CommonFunction-Modules/DevTools/UploadPackage/getPluginVersion.sh`

# 尝试删除本地build分支
git branch -D "$BUILD_BRANCH" || echo "$BUILD_BRANCH not found"
# 如果有云端build的话，拉成本地build
if ! git checkout -t "origin/$BUILD_BRANCH"
then
  # 没有云端build，新建本地build
  git checkout -b $BUILD_BRANCH
fi


print_section_header "清理本地工作区"
# 干净的本地工作区
git reset --hard HEAD && git clean -df
git submodule foreach 'git fetch'
git submodule foreach 'git reset --hard HEAD && git clean -df'
print_section_footer


print_section_header "开始合并"
# 开始合并
git merge -X theirs --commit --no-edit "origin/$CODE_BRANCH" || { echo "自动合并 origin/$CODE_BRANCH 到 build 分支失败，请手动合并后推送到 origin/build 再运行本脚本" >&2; exit 2; }
git submodule update --recursive --
print_section_footer
print_status


# 把 submodules checkout 到 master (默认是游离的commit)
print_section_header "把子模块指定到相应的commit为master"
git submodule foreach 'git checkout -B master'
print_section_footer
print_status

# 清干净子模块本地工作区
print_section_header "清干净子模块本地工作区"
git submodule foreach 'git reset --hard HEAD && git clean -df'
git submodule foreach 'git --no-pager show'
print_section_footer
print_status

print_section_header "清干净子模块本地工作区"
# 对比$CODE_BRANCH和build分支的版本后，取最大的那个
# 记录build分支的版本号
releaseVersion=`./Modules/Mijia-CommonFunction-Modules/DevTools/UploadPackage/getPluginVersion.sh`
isVersionInvalid() {
  if ! [[ $1 =~ ^[0-9]+.[0-9]+.[0-9]+$ ]]; then
    echo invalid version input: $1
    echo please input correct version
    exit -1
  fi
}
isVersionInvalid $masterVersion
isVersionInvalid $releaseVersion
# replace version as newer version
if [[ $masterVersion > $releaseVersion ]]; then
pluginConfigFile="${project_path}/Main/PluginConfig/index.js" && echo "index file path $pluginConfigFile"
sed -i "" "s/'$releaseVersion'/'$masterVersion'/g" $pluginConfigFile && echo "config version as $version"
fi
print_section_footer


# 是否需要npm install
if [[ "$needInstall" != "" ]]; then
  echo "===需要npm install==="
  cd $project_path/../../
  echo "cd to $PWD"
  # rm -rf ./node_modules && rm -f package-lock.json && npm install
  rm -rf ./node_modules
  installSdkDependencies
  echo "===npm install miot工程成功==="
  cd $project_path
  echo "cd to $PWD"
  rm -rf ./node_modules && rm -f package-lock.json && npm install
  echo "===npm install 主工程成功==="
else
  echo "用户指定无需按照依赖"
fi
print_section_footer
print_status


# 删掉旧的包
rm -r build

# 开始build
npm run build

# 如果build失败，那就退出
[[ -f build/publish.mpkg ]] || { echo "Build失败，请检查出错原因" >&2; exit 2; }

# build成功，commit一下
git add -A
version=`./Modules/Mijia-CommonFunction-Modules/DevTools/UploadPackage/getPluginVersion.sh`
git commit -m "Tag: ${version}"
[[ "$isPushRelease" != "" ]] && git push --set-upstream origin "$BUILD_BRANCH"

# 上传到miot
print_section_header "上传包到miot"
if [[ "$isUpload" != "" ]] ;then
  python Modules/Mijia-CommonFunction-Modules/DevTools/UploadPackage/UploadPackage.py || echo "上传包到miot失败"
else
  echo "用户设置不用上传到miot"
fi
print_section_footer

# 运行pkg对比工具
if [[ $DIFF_VERSION == "" ]]; then
  node Modules/Mijia-CommonFunction-Modules/DevTools/buildDiff/diff.js
else
  node Modules/Mijia-CommonFunction-Modules/DevTools/buildDiff/diff.js --v $DIFF_VERSION
fi

# 成功了，happy一下
COMPLETE="脚本运行完成，生成了mpkg"
[[ "$isPushRelease" != "" ]] && COMPLETE+="，推送到了云端"
[[ "$isUpload" != "" ]] && COMPLETE+="并上传到了miot"
echo $COMPLETE
